package com.woniu.payback_font.util;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;

@Component
public class JwtUtil implements Serializable {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 创建一个token字符串
     * @param jwtInfo
     * @return
     */
    public String cerateToken(JwtInfo jwtInfo){
        //获取的jwtBuilder
        JwtBuilder builder = Jwts.builder();

        //设置头部信息
        builder.setHeaderParam("alg",jwtProperties.getAlg());
        builder.setHeaderParam("typ",jwtProperties.getTyp());

        //设置载荷信息
        //设置 Token 签发者 可选
        builder.setIssuer(jwtProperties.getIssuer());
        //设置 Token 的接受者
        builder.setSubject(jwtProperties.getSuject());
        //设置 Token 发布时间
        builder.setIssuedAt(new Date());
        //设置 Token 过期时间
        builder.setExpiration(new Date(new Date().getTime()+jwtProperties.getExpiration()));
        //设置私有字段  jwtBuilder.claim("userCode","0000");
        builder.claim(jwtProperties.getmCode(),jwtInfo.getUserCode());
        builder.claim(jwtProperties.getmName(),jwtInfo.getUserName());

        //这是签名
        builder.signWith(SignatureAlgorithm.HS256,jwtProperties.getSecret());

        String compact = builder.compact();

        return compact;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public Claims verifyAndGetClaimsByToken(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token);
        return claimsJws.getBody();
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    public String getUserCode(String token){
        Claims claims = this.verifyAndGetClaimsByToken(token);
        return (String) claims.get(jwtProperties.getmCode());
    }


}
